<?php
/**
 * DynaGrid - The PHP datagrid
 *
 * @package    DynaGrid
 * @author     $Author: keesschepers $
 * @version    $Id: DataSource.php 15 2011-02-15 17:07:57Z keesschepers $
 */

/**
 * Communication between DynaGrid output function and data Adapter
 *
 * @todo / idea is to make the datasource look for a Adapter responsable for
 * caching any data from the datsource Adapter to prevent a call to this Adapter.
 * Optional should be that anyone could choose there own caching libary like Zend_Cache
 * or write your own (file based perhaps).
 */
class DynaGrid_DataSource {
	protected $arguments = array();

	/**
	 * The Datasource talks with this object to gain meta-data of the data to be
	 * represented in the table grid.
	 *
	 * @var DynaGrid_DataSource_Adapter_Interface
	 */
	public static $dataSourceAdapter;

	/**
	 *
	 * @var DynaGrid_SelectQuery
	 */
	protected $query;
	protected $result;
	protected $data = array();
	protected $columns = array();
	protected $totalRows;
	protected $orderField;
	protected $orderWay;
	public $maxRows;
	public $offset;
	/**
	 * Message which will be displayed when there are no rows found.
	 *
	 * @var string
	 */
	public $norowsmessage;
	public function __construct() {		
	}
	public function __get($property) {
		switch ($property) {
			case 'totalRows' :
			case 'orderWay' :
			case 'orderField' :
				return $this->$property;			
			default :
				throw new DynaGrid_Exception('Unknown property ('.$property.')');
		}
	}
	/**
	 *
	 * Gives a numeric index array containing fieldnames from the datasourceAdapter.
	 * 
	 * @return array
	 */
	public function getColumns() {
		return $this->columns;
	}
	/**
	 * Get the data correspondending to the query.
	 *
	 * @throws DynaGrid_No_Rows_Exception
	 * @return array
	 */
	public function getData() {
		if($this->totalRows == 0) {
			
			include_once 'NoRowsException.php';			
			throw new DynaGrid_NoRowsException($this->norowsmessage);
		}
		return $this->data;
	}
	/**
	 * Get data, metadata, etc
	 *
	 * @return void
	 *
	 */
	public function process(){
		if(!is_null($this->orderField) || !is_null($this->orderWay)) {
			self::$dataSourceAdapter->setOrderBy(array(array(
							'field' => $this->orderField, 
							'direction' => $this->orderWay
			)));
		}

		self::$dataSourceAdapter->setOffset($this->offset);
		self::$dataSourceAdapter->setLimit($this->maxRows);
	
    $this->data = self::$dataSourceAdapter->getData();
    $this->totalRows = self::$dataSourceAdapter->getTotalRows();
		
		$fields = self::$dataSourceAdapter->getFields();

		foreach ($fields as $fieldName) {
			$this->columns[] = $fieldName;
		}
		
	}
	
	public function setOrderWay($orderWay) {
		$this->orderWay = $orderWay;
	}
	
	public function setOrderField($orderField) {
		$this->orderField = $orderField;
	}
}